#include "udpiqreceiver.h"

UdpIqReceiver::UdpIqReceiver(const QHostAddress &groupAddress, quint16 port, QObject *parent)
    : QObject(parent), socket(new QUdpSocket(this))
{
    // 绑定到 AnyIPv4 地址
    socket->bind(QHostAddress::AnyIPv4, port, QUdpSocket::ShareAddress);
    socket->joinMulticastGroup(groupAddress);

    QDir appDir = QCoreApplication::applicationDirPath();

    // 设置 data 文件夹的名称
    QString dataDirName = "data";

    // 创建 data 文件夹的路径
    QDir dataDir(appDir);
    dataDir.mkdir(dataDirName); // 如果 data 文件夹不存在，则创建它

    // 获取 data 文件夹的绝对路径
    QString dataDirPath = dataDir.absolutePath() + QDir::separator() + dataDirName;

    // 创建文件名
    QDateTime now = QDateTime::currentDateTime();
    QString fileName = now.toString("yyyyMMddhhmmss") + ".dat";

    // 构造完整的文件路径
    QString filePath = dataDirPath + QDir::separator() + fileName;

    file = new QFile(fileName);
    file->open(QIODevice::WriteOnly);
    connect(socket, &QUdpSocket::readyRead, this, &UdpIqReceiver::receiveData);
}

UdpIqReceiver::~UdpIqReceiver()
{
    file->close();
    delete socket;
}

void UdpIqReceiver::receiveData()
{
    while (socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        file->write(datagram);
    }
}
